<template>
  <Card>
    <Cond @query="load" :model="pageIn" col="2" :disabled="!parentData.refId">
      <CondItem title="关键字" field="q">
        <Input v-model="pageIn.q" placeholder="名称/key" />
      </CondItem>
      <CondItem title="应用" field="cond.appId">
        <AppCascader v-model="pageIn.cond.appId" @change="load" allowClear />
      </CondItem>
      <template #op>
        <ButtonGroup>
          <Button type="primary" v-drawer="drawerParams" :disabled="!parentData.refId">添加角色</Button>
          <Button type="primary" :disabled="tableSelectDisabled" @click="onDelete">
            {{ tableSelectedMap.size ? `移除角色(${tableSelectedMap.size})` : '移除角色' }}
          </Button>
        </ButtonGroup>
      </template>
    </Cond>
    <Table :data="pageOut.records" @sorter-change="(f, m) => onSort(f, m, load)" :row-selection="tableRowSelect" @selection-change="onTableSelectChange" :loading="loading || saveLoading">
      <TableColumn title="名称" field="name" />
      <TableColumn title="Key" field="key" />
      <TableColumn title="应用" field="appName" />
      <TableColumn title="备注" field="remark" />
      <TableColumn title="创建日期" :width="120" field="createdAt" :sortable="$sortable">
        <template #cell="{ record }">
          <ees-format :value="record.createdAt" pattern="date" />
        </template>
      </TableColumn>
      <TableColumn title="更新日期" :width="120" field="updatedAt" :sortable="$sortable">
        <template #cell="{ record }">
          <ees-format :value="record.updatedAt" pattern="date" />
        </template>
      </TableColumn>
    </Table>
    <ees-page v-model:pageIn="pageIn" :pageOut="pageOut" @change="load" />
  </Card>
</template>

<script setup>
import { Message, Modal, Card, Table, TableColumn, ButtonGroup, Button, Input, Cond, CondItem } from '@idmy/ui'
import { computed, ref, watch } from 'vue'
import { pageByRoleRef, createRoleRef, deleteRolRef } from './services'
import { useLoading, usePage, useDelete, useTableSelect } from '@idmy/core'
import SelectRole from '@/components/role/select.vue'

const { tableRowSelect, tableServerMap, tableSelectDisabled, onTableSelectClear, onTableSelectChange, tableSelectedMap } = useTableSelect()

const props = defineProps({
  dialogOk: Function,
  parentData: {
    type: Object,
    required: true,
    default: () => {
      return {
        redId: null,
        redType: null,
      }
    },
  },
})

const { pageIn, pageOut, onSort } = usePage({
  sorts: ['createdAt', 'desc'],
  condition: {},
})

const parent = computed(() => props.parentData)
const [load, loading] = useLoading(async () => {
  if (Boolean(parent.value.refId) && parent.value.refType) {
    pageOut.value = await pageByRoleRef(pageIn, parent.value.refType, parent.value.refId)
    pageOut.value.records.forEach(item => tableServerMap.set(item.id, item))
  } else {
    pageOut.value = { total: 0, records: [] }
    onTableSelectClear()
  }
})

watch(
  parent,
  () => {
    load()
    onTableSelectClear()
  },
  { immediate: true }
)

const [onOk, saveLoading] = useLoading(async ({ map }) => {
  const arr = []
  map.forEach(item => {
    arr.push({
      roleId: item.id,
      projectId: item.projectId,
      appId: item.appId,
      refType: parent.value.refType,
      refId: parent.value.refId,
    })
  })
  await createRoleRef(arr)
  Message.success('保存成功')
  load()
})

const onDelete = useDelete(async () => {
  const arr = []
  tableSelectedMap.forEach(item => {
    arr.push({
      roleId: item.id,
      refType: parent.value.refType,
      refId: parent.value.refId,
    })
  })
  await deleteRolRef(arr)
  onTableSelectClear()
}, load)

//const onIsInherit = useBoolean(updateRoleIsInherit, load, ['isInherit', '允许继承', '禁止继承'])

const drawerParams = computed(() => {
  return [
    SelectRole,
    `选择角色#2`,
    {
      url: `/api/role/pageByRoleRef/${parent.value.refType}/${parent.value.refId}`,
      condition: { isNot: true },
    },
    onOk,
  ]
})
</script>
